﻿#region directives

using System;
using System.IO;
using System.Xml.Serialization;

#endregion

namespace ToodleDo
{
    public class TokenHelper
    {
        public string Token { get; set; }
        public DateTime Lastupdate { get; set; }
        public string Userid { get; set; }
    }

    public static class TokenStore
    {
        private static readonly string Filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
                                                  @"\token.xml";

        private static TokenHelper _tokenhelper;

        private static TokenHelper StoredToken
        {
            get { return _tokenhelper ?? (_tokenhelper = Load()); }
        }

        public static string UserId
        {
            get { return StoredToken.Userid; }
            set { StoredToken.Userid = value; }
        }


        public static string TokenValue
        {
            get { return StoredToken.Token; }
            set
            {
                StoredToken.Token = value;
                StoredToken.Lastupdate = DateTime.Now;
                Save();
            }
        }

        public static DateTime LastUpdate
        {
            get { return StoredToken.Lastupdate; }
        }

        private static void Save()
        {
            Stream stream = null;
            try
            {
                stream = File.Open(Filename, FileMode.Create);
                XmlSerializer serializer = new XmlSerializer(typeof (TokenHelper));
                serializer.Serialize(stream, _tokenhelper);
                Logger.InvokeMessageEvent("Token saved", Logger.MessageType.Tracking);
            }
            catch (Exception e)
            {
                Logger.InvokeMessageEvent(e.Message, Logger.MessageType.Error);
            }
            finally
            {
                if (stream != null) stream.Close();
            }
        }

        private static TokenHelper Load()
        {
            Stream stream = null;
            TokenHelper t = null;
            try
            {
                stream = File.Open(Filename, FileMode.Open);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof (TokenHelper));
                t = (TokenHelper) xmlSerializer.Deserialize(stream);
            }
            catch (Exception e)
            {
                Logger.InvokeMessageEvent(e.Message,Logger.MessageType.Error);
            }
            finally
            {
                if (stream != null) stream.Close();
                Logger.InvokeMessageEvent("Token loaded", Logger.MessageType.Tracking);
            }
            return t ?? (new TokenHelper());
        }
    }
}